//
//  LLDetailViewController.swift
//  MyEcho
//
//  Created by longlong on 16/1/26.
//  Copyright © 2016年 LongLong. All rights reserved.
//
import MediaPlayer

class LLDetailViewController: UIViewController,PlayerHelperDelegate {
    var music:Music!;
    var playtimerOffset:Double!;
    var currentTime:Double! = 0;
    var isGoPlayingMusic:Bool = false;

    @IBOutlet weak var downButton: UIButton!
    //MARK: user上传者信息
    @IBOutlet weak var userImgView: UIImageView!
    @IBOutlet weak var userNameLabel: UILabel!
    
    //MARK: player播放器信息
    @IBOutlet weak var playImageView: UIImageView!
    @IBOutlet weak var timeLable: UILabel!
    @IBOutlet weak var playCount: UILabel!
    @IBOutlet weak var musicNameLable: UILabel!
    @IBOutlet weak var playerButton: UIButton!
    
    @IBOutlet weak var progressBarView: ProgressBar!
    @IBOutlet weak var timerScrollView: UIView!
    @IBOutlet weak var secondTimerScrollView: UIView!
    
    @IBOutlet weak var progressView: UIView!
    //MARK: 所属频道
    @IBOutlet weak var channelImageView: UIImageView!
    @IBOutlet weak var channelTitleLabel: UILabel!
    
    //MARK: 介绍
    @IBOutlet weak var introduceAuthorLabel: UILabel!
    @IBOutlet weak var introduceTitleLabel: UILabel!
    @IBOutlet weak var introduceContentLabel: UILabel!
    @IBOutlet weak var introduceOriginalLabel: UILabel!
    

    override func viewDidLoad() {
        super.viewDidLoad();
        //开始接受远程事件
        UIApplication.sharedApplication().beginReceivingRemoteControlEvents();
        self.becomeFirstResponder();
        
        //监听后台
         NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onAudioSessionEvent"), name: AVAudioSessionInterruptionNotification, object: nil)
        PlayerHelper.sharePlayerHelper().delegate = self;
        
    }
    override func viewWillAppear(animated: Bool) {
        progressView.frame = CGRectMake(progressView.frame.origin.x, progressView.frame.origin.y, 5, progressView.frame.size.height)
        prepareForPlaying();
    }
    override func viewWillDisappear(animated: Bool) {
         isGoPlayingMusic = false;
    }
    func onAudioSessionEvent(){
        pauseMusic();
    }

    
    //初始化页面信息
    func prepareForPlaying(){
        if  isGoPlayingMusic{
            return;
        }
        
        if !GlobalDataObject.sharedInstance.isFromNetWork{
            //读取本地数据
            let musics =  GlobalDataObject.sharedInstance.locationAry.objectAtIndex(GlobalDataObject.sharedInstance.currentIndex) as! Musics
            let  newMusic = Music();
            newMusic.length = "".stringByAppendingFormat("%d", musics.length)
            newMusic.like_count =  "".stringByAppendingFormat("%d", musics.commentCount)
            newMusic.name = musics.musicName!
            newMusic.pic_500 = musics.pic_200!
            newMusic.source = musics.source!
            newMusic.info = musics.info!
            newMusic.user = ["name":musics.userName!,"avatar_50":musics.userAvatar_50!]
            newMusic.channel = ["name":musics.channelName!,"pic":musics.channelPic!]

            if ((music != nil) && (music.source == newMusic.source)){
                return;
            }
            music = newMusic;
        }else{
            let  newMusic = GlobalDataObject.sharedInstance.arrayData.objectAtIndex(GlobalDataObject.sharedInstance.currentIndex) as! Music;
            
            if (music != nil) && (music.source == newMusic.source) {
                return;
            }
            music = newMusic;
        }

        //user上传者信息
        self.userNameLabel.text = music.user.objectForKey("name") as? String;
        self.userImgView.layer.cornerRadius = self.userImgView.frame.size.width/2;
        self.userImgView.layer.masksToBounds = true;
        self.userImgView.sd_setImageWithURL(NSURL.init(string: (music.user.objectForKey("avatar_50") as? String)!), placeholderImage: nil);
        
        //所属频道
        if music.channel != nil{
            self.channelTitleLabel.text = music.channel.objectForKey("name") as? String;
            self.channelImageView.sd_setImageWithURL(NSURL.init(string: (music.channel.objectForKey("pic") as? String)!), placeholderImage: nil);
        }else{
            self.channelTitleLabel.text = GlobalDataObject.sharedInstance.channel.name as String ;
            self.channelImageView.sd_setImageWithURL(NSURL.init(string: (GlobalDataObject.sharedInstance.channel.pic_100 as String)), placeholderImage: nil);
        }
        
        self.playImageView.sd_setImageWithURL(NSURL.init(string:music.pic_500 as String), placeholderImage: nil) {(image, error, cacheType, imageURL) -> Void in
            self.configNowPlayingInfoCenter();
        }
        self.playImageView.sd_setImageWithURL(NSURL.init(string:music.pic_500 as String), placeholderImage: nil);
        self.musicNameLable.text = music.name as String;
        self.timeLable.text = "00:00";
        
        if music.like_count.integerValue<10000{
            self.playCount.text = music.like_count.stringByAppendingString("次收听");
        }else{
            self.playCount.text = "".stringByAppendingFormat("%.1f万次收听", music.like_count.floatValue/10000.0);
        }
        //介绍
        self.introduceAuthorLabel.text = music.user.objectForKey("name") as? String;
        self.introduceTitleLabel.text = music.name as String;
        
        if !GlobalDataObject.sharedInstance.isFromNetWork{
            self.introduceContentLabel.text = music.info as String;
        }else{
            getMusicDetailInfo(music.ID);
        }
        getMusicComment(music.ID, page: 1)


        //进度条
        let totalTime = self.music.length.doubleValue;
        let width = Double( UIScreen.mainScreen().bounds.size.width);
        playtimerOffset = width / totalTime;
        
        self.progressBarView.result = {
            PlayerHelper.sharePlayerHelper().seekToTime(self.progressBarView.xpoint / self.playtimerOffset)

            //进度条
            self.timerScrollView.frame = CGRectMake(self.timerScrollView.frame.origin.x, self.timerScrollView.frame.origin.y, CGFloat(self.progressBarView.xpoint), self.timerScrollView.frame.size.height);
            self.secondTimerScrollView.frame = CGRectMake(CGFloat(self.progressBarView.xpoint), self.secondTimerScrollView.frame.origin.y, self.secondTimerScrollView.frame.size.width, self.secondTimerScrollView.frame.size.height);
            
            //时间刷新
            self.timeLable.text = self.timeFormatted(NSInteger(self.progressBarView.xpoint / self.playtimerOffset)) as String;
        }
        configNowPlayingInfoCenter();
        startMusic();
    }
    
    @IBAction func clickButton(sender: UIButton) {
        sender.selected = !sender.selected;
        if(sender.selected){
            pauseMusic();
        }else{
            playMusic();
        }
    }
    //MARK:获取音乐详情，评论
    func getMusicDetailInfo(soundID:NSString){
        AFAppDotNetAPIClient.sharedClient().GET(AllDefine.musicDetailURLWith(soundID) as String, parameters: nil, success: {(task: NSURLSessionDataTask?, JSON: AnyObject?) -> Void in
            if (JSON is NSDictionary){
                let dic =  JSON as? NSDictionary ;
                if (dic?.objectForKey("message")?.isEqual("success") != nil){
                    //处理音乐详情
                    self.introduceContentLabel.text = dic?.objectForKey("result")?.objectForKey("info") as? String;
                    self.music.info = self.introduceContentLabel.text!
                }
            }else{
                print("音乐详情：获取数据失败")
            }
            }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
                print("音乐详情:\(error!)");
        }
    }
    
    func getMusicComment(soundID:NSString,page:NSInteger){
        AFAppDotNetAPIClient.sharedClient().GET(AllDefine.commentURLWith(soundID, page: page) as String, parameters: nil, success: {(task: NSURLSessionDataTask?, JSON: AnyObject?) -> Void in
            if (JSON is NSDictionary){
                let dic =  JSON as? NSDictionary ;
                if (dic?.objectForKey("message")?.isEqual("success") != nil){
                    if page==1 {
                    }
                }
            }else{
                print("获取评论：获取数据失败")
            }
            
            }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
                print("获取评论：\(error!)");
        }
        

    }
    
    //MARK:PlayerHelperDelegate
    func playingWithTime(time: NSTimeInterval) {
        currentTime = time;
        changeProgress()
        
        //到时间停止
        if (NSInteger(time) == music.length.integerValue) {
            return;
        }
        
        //进度条
        self.timerScrollView.frame = CGRectMake(self.timerScrollView.frame.origin.x, self.timerScrollView.frame.origin.y, CGFloat( time *  playtimerOffset), self.timerScrollView.frame.size.height);
        self.secondTimerScrollView.frame = CGRectMake(CGFloat( time *  playtimerOffset), self.secondTimerScrollView.frame.origin.y, self.secondTimerScrollView.frame.size.width, self.secondTimerScrollView.frame.size.height);
        
        //时间刷新
        self.timeLable.text = timeFormatted(NSInteger(time)) as String;

    }
    func didStop() {
        nextMusic();//下一首
    }
    
    
    //MARK:音乐播放控制
    func startMusic(){
        PlayerHelper.sharePlayerHelper().playInternetMusicWithURL(self.music.source as String, withDownButton: downButton)
        self.playerButton.selected = false;
    }
    
    //继续播放音乐
    func playMusic(){
        PlayerHelper.sharePlayerHelper().play();
        self.playerButton.selected = false;
    }
    //暂停
    func pauseMusic(){
        PlayerHelper.sharePlayerHelper().pause();
        self.playerButton.selected = true ;
    }

    //下一曲
    func nextMusic(){
        if GlobalDataObject.sharedInstance.isFromNetWork{
            if((GlobalDataObject.sharedInstance.currentIndex+1)<GlobalDataObject.sharedInstance.arrayData.count){
                GlobalDataObject.sharedInstance.currentIndex = GlobalDataObject.sharedInstance.currentIndex + 1;//竟然不能＋＋ 让活不让活了
            }else{
                GlobalDataObject.sharedInstance.currentIndex = 0;
            }
        }else{
            print(GlobalDataObject.sharedInstance.currentIndex )
            if((GlobalDataObject.sharedInstance.currentIndex+1)<GlobalDataObject.sharedInstance.locationAry.count){
                GlobalDataObject.sharedInstance.currentIndex = GlobalDataObject.sharedInstance.currentIndex + 1;//竟然不能＋＋ 让活不让活了
            }else{
                GlobalDataObject.sharedInstance.currentIndex = 0;
            }
        }


        prepareForPlaying();
    }
    
    //上一曲
    func previousMusic(){
        if((GlobalDataObject.sharedInstance.currentIndex-1)<0){
            if GlobalDataObject.sharedInstance.isFromNetWork{
                GlobalDataObject.sharedInstance.currentIndex = GlobalDataObject.sharedInstance.arrayData.count-1;
            }else{
                GlobalDataObject.sharedInstance.currentIndex = GlobalDataObject.sharedInstance.locationAry.count-1;

            }
        }else{
            GlobalDataObject.sharedInstance.currentIndex = GlobalDataObject.sharedInstance.currentIndex - 1;
        }
        prepareForPlaying();
    }
    
    
    //锁屏信息
    func configNowPlayingInfoCenter(){
        if (NSClassFromString("MPNowPlayingInfoCenter") != nil){
            var dict = Dictionary<String,AnyObject>();
            dict[MPMediaItemPropertyArtist] = music.name
            if music.channel != nil{
                dict[MPMediaItemPropertyAlbumTitle] = music.user.objectForKey("name")
            }else{
                dict[MPMediaItemPropertyAlbumTitle] = GlobalDataObject.sharedInstance.channel.name
            }
            if self.playImageView.image != nil{
                dict[MPMediaItemPropertyArtwork] = MPMediaItemArtwork.init(image: self.playImageView.image!)
            }
            dict[MPMediaItemPropertyPlaybackDuration] =  NSNumber.init(double: self.music.length.doubleValue)
            dict[MPNowPlayingInfoPropertyElapsedPlaybackTime] =  NSNumber.init(double: self.currentTime)
            MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = dict
        }
    }
    
    func changeProgress(){
        var dict  = MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo;
        dict?[MPNowPlayingInfoPropertyElapsedPlaybackTime] =  NSNumber.init(double: self.currentTime)
        if (dict?[MPMediaItemPropertyArtwork] == nil && self.playImageView.image != nil) {
            dict?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork.init(image: self.playImageView.image!)
        }
        MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = dict ;
    }

    
    //MARK:时间格式化
    func timeFormatted(totalSeconds:NSInteger)->NSString{
        let seconds  =  totalSeconds % 60;
        let minutes = totalSeconds / 60 ;
        return  "".stringByAppendingFormat("%02d:%02d",minutes, seconds);
    }
    
    //MARK:离线音乐
    @IBAction func getMusicFromNetWork(sender: UIButton) {
        self.downButton.enabled = false;
        progressView.frame = CGRectMake(progressView.frame.origin.x, progressView.frame.origin.y, 5, progressView.frame.size.height)
        getMusicFromNetWork();
    }
    
    func getMusicFromNetWork(){
        
        let manager = AFURLSessionManager(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let request = NSURLRequest(URL: NSURL(string:music.source as String)!)
        
        var progress: NSProgress?
        let downloadTask = manager.downloadTaskWithRequest(request, progress:&progress, destination: { (targetPath, response) -> NSURL! in
                let  cacheDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true).first
                let  path = cacheDir?.stringByAppendingFormat("/%@.mp3",self.music.source.componentsSeparatedByString("?").last!)
                let datas:NSData = NSData.init(contentsOfURL: targetPath)!;
                datas.writeToFile(path!, atomically: true)
                return  NSURL(string:path!);
            }) { (response, filePath, error) -> Void in
                if error == nil{
                    print("音乐下载成功");
                    Musics.addMusics(self.music,channel: GlobalDataObject.sharedInstance.channel)
                }else{
                    self.downButton.enabled = true;
                }
        }
        progress?.addObserver(self, forKeyPath: "fractionCompleted", options:  NSKeyValueObservingOptions.New, context: nil)
        downloadTask.resume()
    }
    
    //设置下载进度
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if keyPath == "fractionCompleted" {
            let progress = object as! NSProgress
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.progressView.frame = CGRectMake(self.progressView.frame.origin.x, self.progressView.frame.origin.y,CGFloat(progress.fractionCompleted)*UIScreen.mainScreen().bounds.size.width, self.progressView.frame.size.height)
            })
        }
    }
    
    
}


//func getDataFromNetWork(){
//    let me:Dictionary = ["act":"login","app":"index","password":"2995750","device_token":"0","v":"9","device_type":"ios","username":"13264280150"];
//    AFAppDotNetAPIClient.sharedClient().POST("http://echosystem.kibey.com/index/login", parameters: me, success: { (task: NSURLSessionDataTask?, JSON: AnyObject?) -> Void in
//        if (JSON is NSDictionary){
//            let dic =  JSON as? NSDictionary ;
//            if (dic?.objectForKey("message")?.isEqual("success") != nil){
//                self.getSound();
//                print("主页：获取数据成功");
//            }
//        }else{
//            print("主页：获取数据失败")
//        }
//        
//        }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
//            print("获取数据失败:\(error!)");
//            
//    }
//}
//func getSound(){
//    AFAppDotNetAPIClient.sharedClient().GET("http://echosystem.kibey.com/sound/info?sound_id=372655", parameters: nil, success: {(task: NSURLSessionDataTask?, JSON: AnyObject?) -> Void in
//        if (JSON is NSDictionary){
//            let dic =  JSON as? NSDictionary ;
//            if (dic?.objectForKey("message")?.isEqual("success") != nil){
//                print("主页：获取数据成功");
//            }
//        }else{
//            print("主页：获取数据失败")
//        }
//        
//        }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
//            print("获取数据失败:\(error!)");
//    }
//}

